/*
 * This file is part of espanso.
 *
 * Copyright (C) 2019-2021 Federico Terzi
 *
 * espanso is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * espanso is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with espanso.  If not, see <https://www.gnu.org/licenses/>.
 */

use anyhow::Result;
use std::collections::HashMap;
use yaml_rust::{Yaml, YamlEmitter};

use crate::convert::ConvertedFile;

pub fn render(converted_files: HashMap<String, ConvertedFile>) -> Result<Vec<(String, String)>> {
  let mut output = Vec::new();
  for (file, content) in converted_files {
    let rendered = render_file(content)?;
    output.push((file, rendered));
  }
  Ok(output)
}

fn render_file(file: ConvertedFile) -> Result<String> {
  let mut dump_str = String::new();
  let mut emitter = YamlEmitter::new(&mut dump_str);
  emitter.multiline_strings(true);
  emitter.dump(&Yaml::Hash(file.content))?;

  let lines: Vec<&str> = dump_str.lines().collect();
  let header = format!("# Original file: {}", file.origin);
  let mut output_lines: Vec<&str> = vec![
    "# Automatically generated by espanso migration tool",
    &header,
    "",
  ];
  if !lines.is_empty() {
    output_lines.extend(&lines[1..]);
  }

  let output = output_lines.join("\n");
  Ok(output)
}
